<?php
namespace  app\index\controller;
use think\Controller;
class Base extends Controller{
    
    public $city="";
    public $account="";
    
    public function _initialize() {
       //城市数据
        $citys=model("City")->getNormalCitys();
       
        $this->getCity($citys);
         //商品分类
        $cats=$this->getRecommendCats();
        $controler=strtolower(request()->controller());
        $title="o2o电商";
        $this->assign('citys', $citys);
        $this->assign('city',$this->city);
        $this->assign('title',$title);
        $this->assign('controler',$controler);
        $this->assign('cats',$cats);
        $this->assign("user",$this->getLoginUser());
       
    }
     //用户登陆
     public function getLoginUser() {
        if(!$this->account) {
            $this->account = session('o2o_user', '', 'o2o');
        }
        return $this->account;
    }
    
    //获取城市city
    public function getCity($citys){
       foreach($citys  as $city){
          $city=$city->toArray();//数组
          if($city['is_default'] == 1) {
                $defaultuname = $city['uname'];
                break; // 终止foreach
            }
       }
       //默认城市->根据uname来切换城市...
       $defaultuname=$defaultuname ? $defaultuname:"nanking";
        if(session("cityuname","","o2o") && !input('get.city')){//判断如果没有选择
               $cityuname = session('cityuname', '', 'o2o');
        }else{
               $cityuname=input("get.city",$defaultuname,"trim");   
                session("cityuname",$cityuname,"o2o");
        }
       
        $this->city=model("City")->where(['uname'=>$cityuname])->find();
        
    }
    
    /**
     * 获取首页推荐当中中的商品分类数据
     */
    public function getRecommendCats(){
        $parentIds=$sedcatArr=$recomCats=[];
       
        $cats=model("Category")->getNormalRecommendCategoryByParentId(0,5);
          foreach($cats as $cat){
             $parentIds[]=$cat->id;   //为了获取parentids
          }
         //获取二级分类 
         $sedCats=model("Category")->getNormalCategoryIdParentId($parentIds);
           foreach($sedCats as $sedcat){
               $sedcatArr[$sedcat->parent_id][]=[
                           "id"=>$sedcat->id,
                           "name"=>$sedcat->name,
               ];
           }
           //获取一级和二级分类(可选)
           foreach($cats as $cat){
                //第一个参数是一级数据的值, 第二个参数是所有的二级数值
              $recomCats[$cat->id]=[$cat->name,empty($sedcatArr[$cat->id]) ? [] : $sedcatArr[$cat->id]];
           }
           return $recomCats;
           
    }
    
    
}
